#include <cstdio>
#include <map>
#include <sstream>
#include <string>

#include <include/core/SkFontMgr.h>
#include <include/core/SkString.h>
#include <src/core/SkFontDescriptor.h>

#include "typeface.h"

int main(int argc, char **argv)
{
    std::map<std::string, std::vector<std::string>> families;
    std::map<std::string, std::shared_ptr<Typeface>> typefaces;
    SkString name;
    auto fm = SkFontMgr::RefDefault();
    for (int i = 0; i < fm->countFamilies(); i++) {
        fm->getFamilyName(i, &name);
        std::string familyName = name.c_str();
        std::string weightName = "";
        auto pos = familyName.find_last_of(' ');
        if (pos != std::string::npos) {
            auto extra = familyName.substr(pos + 1);
            const char *weights[] = {
                "Bold", "bold",
                "Light", "Lt",
                "Heavy",
                "Medium", "Med", "Md",
                "Normal",
                "Thin", "Th",
                "Black", "Blk", "Bk",
            };
            for (auto weight : weights) {
                if (extra.find(weight) != std::string::npos) {
                    weightName = extra;
                    familyName = familyName.substr(0, pos);
                }
            }
        }
        families[familyName].push_back(weightName);
        if (weightName == "") {
            typefaces[familyName] = std::make_shared<Typeface>(fm->createStyleSet(i)->matchStyle({}));
        }
    }

    if (argc == 1) {
        int32_t index = 0;
        for (auto &[familyName, weightNames] : families) {
            printf("\033[31m%d: \033[32m%s \033[34m[", index++, familyName.c_str());
            for (auto &weightName : weightNames) {
                printf("%s, ", weightName.c_str());
            }
            printf("\b\b]\033[0m\n");
        }
        return 0;
    }

    if (argc == 2) {
        int32_t index = 0;
        std::stringstream ss;
        int32_t codepoint;
        ss << argv[1];
        ss >> codepoint;
        for (auto &[familyName, typeface] : typefaces) {
            if (typeface->Has(codepoint)) {
                printf("%d: %s\n", index++, familyName.c_str());
            }
        }
    }
    return 0;
}
